package com.zzyl.nursing.service.impl;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.nursing.domain.CancelRequest;
import com.zzyl.nursing.domain.DoTask;
import com.zzyl.nursing.dto.NursingTaskDto;
import com.zzyl.nursing.dto.TaskDto;
import com.zzyl.nursing.vo.NursingTaskVo;
import com.zzyl.nursing.vo.NusringTaskIdVo;
import com.zzyl.oss.client.OSSAliyunFileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.NursingTaskMapper;
import com.zzyl.nursing.domain.NursingTask;
import com.zzyl.nursing.service.INursingTaskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.stream.Collectors;

/**
 * 护理任务Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-25
 */
@Service
public class NursingTaskServiceImpl extends ServiceImpl<NursingTaskMapper, NursingTask> implements INursingTaskService {
    @Autowired
    private NursingTaskMapper nursingTaskMapper;
    @Autowired
    private OSSAliyunFileStorageService fileStorageService;

    /**
     * 查询护理任务
     *
     * @param id 护理任务主键
     * @return 护理任务
     */
 @Override
public NusringTaskIdVo selectNursingTaskById(Long id) {
    NusringTaskIdVo nusringTaskIdVo = nursingTaskMapper.selectNursingTaskById(id);

    // 查询护理员名称
    if (nusringTaskIdVo != null && nusringTaskIdVo.getNursingId() != null) {
        String nursingIdStr = nusringTaskIdVo.getNursingId();
        List<String> nursingNames = new ArrayList<>();

        // 检查字符串是否有效
        if (StrUtil.isNotEmpty(nursingIdStr)) {
            // 拆分字符串为ID数组（按逗号分割）
            String[] nursingIdArray = nursingIdStr.split(",");

            // 循环查询每个护理员的姓名
            for (String idStr : nursingIdArray) {
                try {
                    // 转换为Long类型ID
                    Long nursingId = Long.valueOf(idStr.trim());
                    // 查询单个护理员姓名
                    String nurseName = nursingTaskMapper.selectNursingName(nursingId);
                    if (StrUtil.isNotEmpty(nurseName)) {
                        nursingNames.add(nurseName);
                    }
                } catch (NumberFormatException e) {
                    // 处理ID格式错误的情况
                    log.error("护理员ID格式错误：" + idStr, e);
                }
            }
        }

        // 设置护理员姓名列表
        nusringTaskIdVo.setNursingName(nursingNames);
    }

    return nusringTaskIdVo;
}


    /**
     * 查询护理任务列表
     *
     * @param nursingTask 护理任务
     * @return 护理任务
     */
    @Override
    public List<NursingTask> selectNursingTaskList(NursingTask nursingTask) {
        return nursingTaskMapper.selectNursingTaskList(nursingTask);
    }

    /**
     * 新增护理任务
     *
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int insertNursingTask(NursingTask nursingTask) {

        return save(nursingTask) ? 1 : 0;
    }


    /**
     * 取消护理任务
     *
     * @param cancelRequest 护理任务
     * @return 结果
     */
    @Override
    public int updateNursingTask(CancelRequest cancelRequest) {
        // 通过Spring Security获取当前登录用户
        try {
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            cancelRequest.setExecutor(username);
        } catch (Exception e) {
            // 如果获取失败，使用默认值
            cancelRequest.setExecutor("unknown");
        }
        cancelRequest.setRealServerTime(LocalDateTime.now());
        //设置修改时间
        cancelRequest.setUpdateTime(LocalDateTime.now());
        return nursingTaskMapper.cancel(cancelRequest);
    }

    /**
     * 批量删除护理任务
     *
     * @param ids 需要删除的护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除护理任务信息
     *
     * @param id 护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 执行任务
     *
     * @param doTask
     * @return
     */
    @Override
    public int doTask(DoTask doTask) {
        doTask.setStatus(2);
        // 如果有图片数据，先上传图片到OSS
        if (doTask.getTaskImage() != null && !doTask.getTaskImage().isEmpty()) {
            // 判断是否为Base64格式的图片数据
            if (doTask.getTaskImage().startsWith("data:image")) {
                try {
                    // 处理Base64图片数据
                    String base64Data = doTask.getTaskImage().substring(doTask.getTaskImage().indexOf(",") + 1);
                    byte[] imageBytes = Base64.getDecoder().decode(base64Data);
                    InputStream inputStream = new ByteArrayInputStream(imageBytes);

                    // 生成文件名
                    String fileName = "nursing/tasks/" + doTask.getTaskId() + "/" + UUID.randomUUID() + ".jpg";

                    // 上传到OSS
                    String imageUrl = fileStorageService.store(fileName, inputStream);

                    // 将返回的URL设置回doTask
                    doTask.setTaskImage(imageUrl);
                } catch (Exception e) {
                    log.error("上传护理任务图片失败，任务ID: {}", e);
                }
            }
        }
        // 通过Spring Security获取当前登录用户
        try {
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            doTask.setExecutor(username);
        } catch (Exception e) {
            // 如果获取失败，使用默认值
            doTask.setExecutor("unknown");
        }
        // 更新数据库
        return nursingTaskMapper.updateDo(doTask);
    }

    /**
     * 取消任务
     * @param dto
     * @return
     */
    @Override
    public int updateNursingTaskCancel(TaskDto dto) {
        //根据任务ID查询
        NursingTask nursingTask = nursingTaskMapper.selectById(dto.getTaskId());
        //状态改为已取消
        if (nursingTask != null) {
            nursingTask.setStatus(3);
        }
        //将Dto转换为实体
        nursingTask.setCancelReason(dto.getReason());
        nursingTask.setUpdateTime(new Date());
        //设置更新人，需要拿到当前登录用户
        nursingTask.setUpdateBy(SecurityUtils.getUsername());

        //更新数据库
        return nursingTaskMapper.updateNursingTask(nursingTask);
    }

    /**
     * 分页查询
     *
     * @param dto
     * @return
     */

    @Override
    public Page<NursingTask> selectNursingTaskAllList(NursingTaskDto dto) {
        // 设置分页信息
        Page<NursingTask> page = new Page<>(dto.getPageNum(), dto.getPageSize());

        // 设置查询条件
        LambdaQueryWrapper<NursingTask> queryWrapper = new LambdaQueryWrapper<>();

        // 老人姓名模糊查询
        if (StrUtil.isNotEmpty(dto.getElderName())) {
            queryWrapper.like(NursingTask::getElderName, dto.getElderName());
        }
        // 护理员ID精确查询
        if (dto.getNurseId() != null) {
            queryWrapper.eq(NursingTask::getNursingId, dto.getNurseId());
        }
        // 项目ID精确查询
        if (dto.getProjectId() != null) {
            queryWrapper.eq(NursingTask::getProjectId, dto.getProjectId());
        }
        // 期望服务时间范围查询
        if (dto.getStartTime() != null && dto.getEndTime() != null) {
            queryWrapper.between(NursingTask::getEstimatedServerTime, dto.getStartTime(), dto.getEndTime());
        }
        // 状态精确查询
        if (dto.getStatus() != null) {
            queryWrapper.eq(NursingTask::getStatus, dto.getStatus());
        }

        // 执行查询
        page = this.page(page, queryWrapper);

        // 查询护理员名称（处理字符串类型的多个护理员ID）
        page.getRecords().forEach(task -> {
            // 获取存储护理员ID的字符串（如 "101,102,103"）
            String nursingIdStr = task.getNursingId();
            List<String> nursingNames = new ArrayList<>();

            // 检查字符串是否有效
            if (StrUtil.isNotEmpty(nursingIdStr)) {
                // 拆分字符串为ID数组（按逗号分割）
                String[] nursingIdArray = nursingIdStr.split(",");

                // 循环查询每个护理员的姓名
                for (String idStr : nursingIdArray) {
                    try {
                        // 转换为Long类型ID
                        Long nursingId = Long.valueOf(idStr.trim());
                        // 查询单个护理员姓名
                        String nurseName = nursingTaskMapper.selectNursingName(nursingId);
                        if (StrUtil.isNotEmpty(nurseName)) {
                            nursingNames.add(nurseName);
                        }
                    } catch (NumberFormatException e) {
                        // 处理ID格式错误的情况
                        throw new RuntimeException("护理员ID格式错误：" + idStr);
                    }
                }
            }

            // 设置护理员姓名列表
            task.setNursingName(nursingNames);
        });

        return page;
    }      /**
             * 修改时间
             *
             * @param doTask
             * @return
             */
            @Override
            public int updateTime (DoTask doTask){
                return nursingTaskMapper.updateTime(doTask);
            }
        }